package com.wind.cloud.zero.gateway.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import com.wind.cloud.zero.gateway.handler.HystrixFallbackHandler;

import lombok.AllArgsConstructor;

@Configuration
@AllArgsConstructor
public class RouterFunctionConfiguration
{
    private final HystrixFallbackHandler hystrixFallbackHandler;

    @Bean
    public RouterFunction<?> routerFunction()
    {
        return RouterFunctions
                .route(RequestPredicates.path("/test"),
                        request -> ServerResponse.ok().body(BodyInserters.fromObject("hello")))
                .andRoute(RequestPredicates.path("/fallback").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                        hystrixFallbackHandler);
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder)
    {
        return builder.routes().route(r -> r.path("/baidu/header").filters(f -> f.addResponseHeader("token", "mytoken"))
                .uri("http://baidu.com:80/")).build();
    }
}